package com.zyh.annotation.demo5;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author zyh
 * @Date 2024/8/15 10:46
 * @Description
 */
public class AnnotationDemo5 {
    public static void main(String[] args) throws Exception {
        Book book = new Book("红楼梦", new Date());
        //拿到字节码文件对象
        Class c = book.getClass();
        //拿到所有的属性
        Field[] declaredFields = c.getDeclaredFields();
        //遍历所有的属性
        for (Field declaredField : declaredFields) {
            //打开访问开关
            declaredField.setAccessible(true);
            //判断属性上是否有 MyJsonFormat 注解
            if (declaredField.isAnnotationPresent(MyJsonFormat.class)) {
                //拿到注解对象
                MyJsonFormat annotation = declaredField.getAnnotation(MyJsonFormat.class);
                //拿到注解的值
                String pattern = annotation.pattern();
                //拿到属性的值
                Date fieldValue = (Date) declaredField.get(book);
                //格式转换
                String newFieldValue = new SimpleDateFormat(pattern).format(fieldValue);
                System.out.println("newFieldValue = " + newFieldValue);
            }
        }
        System.out.println(book);
    }
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyJsonFormat {
    String pattern();
}
